package com.trtan.hr.service;

import com.trtan.hr.dao.IconDao;
import com.trtan.hr.pojo.Icon;
import com.trtan.hr.pojo.RespPageEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author: trtan
 * @create: 2021-04-02 09:03
 * @description: 从Element-UI https://element.eleme.cn/#/zh-CN/component/icon中爬取图标并存储
 *               分析发现css文件中有对图标进行样式的设置
 *               所以爬取css文件再以正则表达式提取满足图标前缀的格式的字符串
 *               再去重，最后将获取的图标插入到数据库中
 **/
@Service
public class IconService {
    static final Integer SUCCESS = 200;
    static final String url = "https://element.eleme.cn/element-ui.3668a6a.css";
    static final String regex = "\\.el-icon[A-Za-z-]*:";
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    IconDao iconDao;

    @Transactional(rollbackFor = Exception.class)
    public void addIcons() throws IOException {
        String[] icons = new IconService().getIcons();
        if (iconDao == null) {
            logger.error("bad");
        } else {
            iconDao.truncateTable();
            for (int i = 0; i < icons.length; i++) {
                Icon icon = new Icon();
                icon.setClassText(icons[i]);
                icon.setRef(url);
                icon.setId(0);
                iconDao.insert(icon);
            }
            logger.info("成功添加" + icons.length + "个图标");
        }
    }

    private String getText() throws IOException {
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestMethod("GET");
        conn.setUseCaches(false);
        conn.setConnectTimeout(10000);
        conn.connect();
        Map<String, List<String> > map = conn.getHeaderFields();
        for (String key : map.keySet()) {
            System.out.println(key + " " + map.get(key));
        }
        StringBuffer sb = new StringBuffer();
        if (conn.getResponseCode() == SUCCESS) {
            InputStream in = conn.getInputStream();
            if (null != in) {
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
                String line = null;
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                }
                br.close();
            }
        }
        return sb.toString();
    }

    private String[] getIcons() throws IOException {
        String text = getText();
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(text);
        Set<String> icons = new HashSet<>();
        while (m.find()) {
            icons.add(m.group().substring(1, m.group().length() - 1));
        }
        String[] array = new String[icons.size()];
        icons.toArray(array);
        return array;
    }

    public RespPageEntity selectAll(Integer page, Integer size) {
        RespPageEntity entity = new RespPageEntity();
        if (page != null && size != null) {
            page = (page - 1) * size;
        }
        List<String> allIcons = iconDao.getAllIcons(page, size);
        Long total = iconDao.getTotal();
        entity.setData(allIcons);
        entity.setTotal(total);
        return entity;
    }
}
